package com.util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 创建faceset
 *
 * @author 蔡文欣
 * @date 2023/06/28 09:35:42
 */
public class CreateFaceset {
    /**
     * 创建类面集
     *
     * @param className 类名
     * @return {@link String}
     */
    public static String CreateClassFaceSet(String className) {
        String api_key = "7Qd7y5LflV5udF7sVgS01MPzNLgeuTWA";
        String api_secret = "jTxK14YcqHlLWdepWnnomTbzh_OkZGtc";
        String faceset_name = className;
        String state = "";
        try {
            // 构建请求URL和Payload
            URL url = new URL("https://api-cn.faceplusplus.com/facepp/v3/faceset/create");
            String data = "api_key=" + URLEncoder.encode(api_key, "UTF-8") +
                    "&api_secret=" + URLEncoder.encode(api_secret, "UTF-8") +
                    "&display_name=" + URLEncoder.encode(faceset_name, "UTF-8");


            // 创建连接并发送请求
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            System.out.println("开始创建人脸库...");

            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.writeBytes(data);
            out.flush();
            out.close();
            /*https://api-cn.faceplusplus.com/imagepp/v1/facealbum/deletealbum*/
            // 处理响应结果
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                System.out.println("API返回数据：" + response);
                JSONObject jsonObject = new JSONObject(response.toString());
                if (jsonObject.has("faceset_token")) {
                    String faceset_token = jsonObject.getString("faceset_token");
                    System.out.println("人脸库创建成功！Faceset Token为：" + faceset_token);
                    state = "人脸库创建成功！Faceset Token为：" + faceset_token;
                } else {
                    state = "无法从API返回结果中获取faceset_token字段！";
                    throw new JSONException("无法从API返回结果中获取faceset_token字段！");
                }
            } else {
                state = "Face++ API接口调用失败，错误码为" + responseCode;
                throw new RuntimeException("Face++ API接口调用失败，错误码为" + responseCode);
            }
        } catch (JSONException e) {
            System.err.println("JSON解析错误： " + e.getMessage());
            state = "JSON解析错误： " + e.getMessage();
            e.printStackTrace();

        } catch (Exception e) {
            System.err.println("请求异常：" + e.getMessage());
            state = "请求异常：" + e.getMessage();
            e.printStackTrace();

        }
        return state;
    }

    public static void main(String[] args) {
        CreateFaceset.CreateClassFaceSet("顾客人脸库");
    }
}